public class HF_ClientWSImport{
public Id GetAccountID(String PartnerID)
      {
        Account Acccon;
        Id strAccountID = null;
        try{
            if(PartnerID != null){
                Acccon = [Select Id from Account where Partner_ID__c =: PartnerID Limit 1];}
        }
        catch(Exception ex){}
        If(Acccon != null){
            strAccountID = Acccon.Id;}        
        if(strAccountID != null){
            return strAccountID;}
        else{return null;}        
      }
 

  
Public String getStateName(String Code, String CountryCode){
  String strState;
  If(Code != null && CountryCode != null){
          strState = [Select Value_in_SFDC__c from State__c where Value_in_PIMS__c =: code and Country_code__c =: CountryCode Limit 1].Value_in_SFDC__c;
      }
      return strState;
  }    
    
Public String getRelationshipType(String RelationshipCode){ 
    String strRel = ''; 
    If(RelationshipCode != null){ 
    try{
        strRel = [select Value_in_SFDC__c from RelationshipType__c where Value_in_PIMS__c =: RelationshipCode Limit 1].Value_in_SFDC__c; 
    }
    catch(Exception ex){
        strRel = '';
    }
    } 
    return strRel; 
}


Public String getEmailType(String EmailCode){ 
    String strem = ''; 
    If(EmailCode != null){ 
        try{
        strem = [select Value_in_SFDC__c from EmailType__c where Value_in_PIMS__c =: EmailCode Limit 1].Value_in_SFDC__c; 
    }
    catch(Exception ex){
        strem = '';
    }
    } 
    return strem; 
}

Public String getphoneType(String PhoneCode){ 
    String strph = ''; 
    If(PhoneCode != null){ 
        try{
        strph = [select Value_in_SFDC__c from PhoneType__c where Value_in_PIMS__c =: PhoneCode Limit 1].Value_in_SFDC__c; 
    }
    catch(Exception ex){
        strph = '';
    }
    } 
    return strph; 
}

Public String getaddrType(String addrCode){ 
    String stradd = ''; 
    If(addrCode != null){ 
        try{
        stradd = [select Value_in_SFDC__c from AddressType__c where Value_in_PIMS__c =: addrCode Limit 1].Value_in_SFDC__c; 
    }
    catch(Exception ex){stradd = '';}
    } 
    return stradd; 
}
Public Boolean getPreferredValue(String preferredval){ 
    Boolean val = false; 
    If(preferredval != null){ 
    try{
             if(preferredval == 'Y'){val = true; }
             else {val = false;}
    }
    catch(Exception ex){
        system.debug('##exception  preferred phone:'+ex);
    }
    }
    return val; 
}
Public String getSalutationValue(String title){ 
    String salutation = ''; 
    If(title != null){ 
        try{
        salutation = [select Value_in_SFDC__c from Salutation__c where Value_in_PIMS__c =: title Limit 1].Value_in_SFDC__c; 
    }
    catch(Exception ex){salutation = '';}
    } 
    return salutation; 
}
Public String getSuffixValue(String suffixpims){ 
    String suffix = ''; 
    If(suffixpims != null){ 
        try{
        suffix = [select Value_in_SFDC__c from Suffix__c where Value_in_PIMS__c =: suffixpims Limit 1].Value_in_SFDC__c; 
    }
    catch(Exception ex){suffix = '';}
    } 
    return suffix; 
}
Public String getStatus(String status){ 
    String sts = ''; 
    If(status != null){ 
        try{
        sts = [select Value_in_SFDC__c from Status__c where Value_in_PIMS__c =:status].Value_in_SFDC__c;
    }
    catch(Exception ex){sts = '';}
    } 
    return sts; 
}
/*
Public String getCountyName(String state, String CountyCode){
  String countyname = '';
    
       If(state != null && CountyCode != null){
        try{
          countyname = [Select Name from county__C where State__c =: state and countyCode__c =: CountyCode Limit 1].Name;
        }catch(Exception ex){countyname = '';}
      }
      return countyname;
  }    
   */  
public string InsertWrapperRecords(WebServiceFinal2.GetContactWrapper wrpcls){
    String Endresult;
    String PartnerId = null;
    Id ContactId;
    Id AccountId;
    String reltype;
    String salutation;
    String suffix;
    String conreltype;
    String Status;
    Set<Id> accountIdList = new Set<Id>();
    Set<String> relationtypeList = new Set<String>();
    List<WebServiceFinal2.RelationshipWrapper> relwr=new List<WebServiceFinal2.RelationshipWrapper>(); 
    List<Contact_Phone__c> Phlist = new List<Contact_Phone__c>();
    WebServiceFinal2.ArrayOfPhoneWrapper arrphone = new WebServiceFinal2.ArrayOfPhoneWrapper();
    List<WebServiceFinal2.PhoneWrapper> phwr=new List<WebServiceFinal2.PhoneWrapper>();
    WebServiceFinal2.ArrayOfRelationshipWrapper arr=new WebServiceFinal2.ArrayOfRelationshipWrapper();  
        If(wrpcls != null){
            If(wrpcls.RelationshipInfo != null){    
                
                arr = wrpcls.RelationshipInfo; 
                relwr = arr.RelationshipWrapper; 
                system.debug('@@@@@ relwr  ;'+relwr);
            If(relwr != null && relwr.size()>0) {
                system.debug('@@@@@ relwr size ;'+relwr.size());
                    for(WebServiceFinal2.RelationshipWrapper r:relwr){
                        system.debug('@@@@@ r.Enddate  ;'+r.Enddate);  
                        system.debug('@@@@@ r.RelatedPartnerID ;'+r.RelatedPartnerID );   
                        If(r.Enddate == null && r.RelatedPartnerID != null){  
                            system.debug('####PartnerContactID'+r.PartnerContactID);                            
                            AccountId = GetAccountID(r.PartnerContactID);
                            system.debug('####AccountId'+AccountId);
                            //AccountId = GetAccountID(r.RelatedPartnerID );
                            reltype= r.RelationshipType;
                            if(reltype!=null){
                             relationtypeList.add(getRelationshipType(reltype));
                            }
                            if(AccountId!=null)
                            {accountIdList.add(AccountId);}
                            Status=getStatus(r.Status);
                        }
                    }
            }                        
            }
        }
        system.debug('@@@@@ Account ID ;'+AccountId );
        If(AccountId != null && relwr!=null && relwr.size()>0){      
        //Contact Insert
            If(wrpcls.ContactInfo != null){
                List<Contact> conList = new List<Contact>();
                    PartnerId = wrpcls.ContactInfo.PartnerContactID;
                    Contact con = new contact();
                    con.Firstname = wrpcls.ContactInfo.FirstName;
                    con.Lastname = wrpcls.ContactInfo.LastName;
                    con.Partner_Contact_ID__c = wrpcls.ContactInfo.PartnerContactID;
                    con.Name_Id__c = String.Valueof(wrpcls.ContactInfo.NameID);
                    con.Middle_Name__c = wrpcls.ContactInfo.MiddleName;
                    con.Preferred_Name__c = wrpcls.ContactInfo.PreferredName;
                    con.Gender__c = Gender__c.getvalues(wrpcls.ContactInfo.gender).Value_in_SFDC__c;
                    con.Status__c = getStatus(wrpcls.ContactInfo.Status);
                    con.AccountID = AccountID;
                    
                    conreltype=getRelationshipType(reltype);
                     system.debug('&&&&&&&conreltype'+ conreltype);
                    if(conreltype!=''){
                        con.Affiliate_Organizational_Role__c=conreltype;
                    }else{
                        con.Affiliate_Organizational_Role__c=reltype;
                    }
                    
                    suffix=getSuffixValue(wrpcls.ContactInfo.Suffix);
                     system.debug('&&&&&&&suffix'+ suffix);
                    if(suffix!='')
                    {con.Suffix__c=suffix;}
                    else
                    {con.Suffix__c=wrpcls.ContactInfo.Suffix;}
                    
                    salutation=getSalutationValue(wrpcls.ContactInfo.Title);
                     system.debug('&&&&&&&salutation'+ salutation);
                    if(salutation !='')
                    {con.Salutation= salutation;}
                    else
                     {con.Salutation=wrpcls.ContactInfo.Title;}
                     
                    conList.add(con);
                If(conList != null && conList.size()>0)
                {
                    Insert conList;
                    system.debug('conList---->'+conList);
                }
                    ContactId = conList[0].id;
                    system.debug('&&&&&&&'+ ContactId);
                }                       
              
        //Address Insert
            If(wrpcls.AddressInfo != null){
                List<Contact_Address__c> addrList = new List<Contact_Address__c>();
                    string PreferredAddress = wrpcls.AddressInfo.PreferredAddress;
                        if(PreferredAddress == 'Y'){
                            PreferredAddress = 'true';}
                        else if(PreferredAddress == 'N'){
                                PreferredAddress = 'false';}
                        else{
                            PreferredAddress = 'false';
                        }
            if(ContactId  != null){          
                system.debug('%%%%%%'+wrpcls.AddressInfo.state);
                system.debug('$$$$$$'+wrpcls.AddressInfo.country);
                Contact_Address__c add = new Contact_Address__c();
                
                    add.Contact__c = ContactId;
                    add.Preferred__c =Boolean.valueOf(PreferredAddress);
                    
                    String s=getaddrType(wrpcls.AddressInfo.AddressType);
                    if(s!='')
                        add.Address_Type__c = s;
                    else
                        add.Address_Type__c =  wrpcls.AddressInfo.AddressType;
                        
                    add.Country__c =  Country__c.getvalues(wrpcls.AddressInfo.Country).Value_in_SFDC__c;   
                    add.Street__c = wrpcls.AddressInfo.StreetAddress;  
                    add.Address_Line1__c = wrpcls.AddressInfo.AddressLine1;               
                    add.Address_Line2__c = wrpcls.AddressInfo.AddressLine2;
                    add.City__c = wrpcls.AddressInfo.city;
                    add.State__c = getStateName(wrpcls.AddressInfo.State,wrpcls.AddressInfo.Country);
                    
                    //County__c = getCountyName(getStateName(wrpcls.AddressInfo.State,wrpcls.AddressInfo.Country),wrpcls.AddressInfo.County),
                    add.Zipcode__c = wrpcls.AddressInfo.zipcode;
                    add.Zipcode_Extn__c = wrpcls.AddressInfo.ZipCodeExtension;
                    add.Status__c = Status__c.getvalues(wrpcls.AddressInfo.Status).Value_in_SFDC__c;
                    add.Comments__c = wrpcls.AddressInfo.Comments;
                    addrList.add(add);
            }
                    system.debug('%%%%%%'+addrList);
                    system.debug('%%%County%%%'+wrpcls.AddressInfo.County);
                    if(addrList != null && addrList.size()>0)
                    {                 
                      insert addrList;
                    }
                }
              
        //Phone Insert
            If(wrpcls.PhoneInfo != null ){
                
                //string PreferredTelephone;
                arrphone = wrpcls.PhoneInfo;
                phwr = arrphone.PhoneWrapper;
                
                if(ContactId  != null){
                   system.debug('connnn'+ContactId);
                   if(phwr !=null && phwr.size()>0){
                   for(WebServiceFinal2.PhoneWrapper phonereccord :phwr){
                       Contact_Phone__c ph = new Contact_Phone__c();
                            ph.Contact__c = ContactId;
                            ph.Preferred__c = getPreferredValue(phonereccord.PreferredPhone);
                             system.debug('****pims PreferredPhone********'+phonereccord.PreferredPhone+'*******'+getPreferredValue(phonereccord.PreferredPhone));
                             
                            ph.Country__c = Country__c.getvalues(phonereccord.country).Value_in_SFDC__c;
                            ph.Phone__c = phonereccord.Phone;
                            if(phonereccord.Extn !=null){
                            	 ph.Extension__c =Integer.valueOf(phonereccord.Extn);
                            }
                            
                            String s=getphoneType(phonereccord.PhoneType);
                            if(s!='')
                                ph.Phone_Type__c = s;
                            else
                                ph.Phone_Type__c = phonereccord.PhoneType;
                                
                            ph.Description__c = phonereccord.comments;
                            ph.Status__c = Status__c.getvalues(phonereccord.status).Value_in_SFDC__c;
    
                             system.debug('************'+ph);
                             Phlist.add(ph);
                   }
                }
                        system.debug('%%%'+Phlist);
                        If(Phlist != null && Phlist.size()>0){
                             insert Phlist;
                        }
                }
            }
                             
        //Email Insert
            If(wrpcls.EmailInfo != null){
                List<Contact_Email__c> Emlist = new list<Contact_Email__c>();
                
                
                system.debug('PPPP-->'+PartnerId );
                if(ContactId  != null){
                    system.debug('connnn'+ContactId);
                    Contact_Email__c em = new Contact_Email__c();
                    em.Contact__c = ContactId ;
                    em.Preferred__c = getPreferredValue(wrpcls.EmailInfo.PreferredEmail);
                    
                    String s= getEmailType(wrpcls.EmailInfo.EmailType);
                    if(s!='')
                        em.Email_Type__c = s;
                    else
                        em.Email_Type__c = wrpcls.EmailInfo.EmailType;
                        
                    em.Email__c = wrpcls.EmailInfo.Email;
                    em.Description__c = wrpcls.EmailInfo.Comments;
                    Emlist.add(em);
                }
                    system.debug('************'+Emlist);
                If(Emlist != null && Emlist.size()>0){
                    insert Emlist;
                }
            }
              
        // Relationship Insert
            If(wrpcls.RelationshipInfo != null){    
                List<Relationship__c> Relist = new List<Relationship__c>();
                List<Relationship__c> RelationshipOldList = new List<Relationship__c>();
         if(accountIdList !=null && accountIdList.size()>0){
                RelationshipOldList = [select Id from Relationship__c where contact__c=:ContactId and account__c IN:accountIdList and Affiliate_Organizational_Role__c IN:relationtypeList and Status__c='Active' and Id !=null];
            
            for(Id accid :accountIdList){
               
                for(WebServiceFinal2.RelationshipWrapper wr :wrpcls.RelationshipInfo.RelationshipWrapper){
                	
                   if(ContactId  != null && accid !=null && RelationshipOldList!=null){
                        
                       for(Relationship__c relationshipold :RelationshipOldList){
                       	
                       	if(accid != relationshipold.account__c && ContactId != relationshipold.contact__c && getRelationshipType(wr.RelationshipType) != relationshipold.Affiliate_Organizational_Role__c){
                        
                        	system.debug('####relationship'+wr);
                            
                            Relationship__c relationshipInsert = new Relationship__c();
                             relationshipInsert .Contact__c = ContactId;
                             relationshipInsert .Account__c = accid;
                             relationshipInsert .Description__c =null;
                             String s=getRelationshipType(wr.RelationshipType);
                             if(s!='')
                                {relationshipInsert .Affiliate_Organizational_Role__c=s;}
                             else
                                {relationshipInsert .Affiliate_Organizational_Role__c= wr.RelationshipType;}
                                
                             if((wr.startdate) !=null)
                             {relationshipInsert .Start_Date__c = Date.valueof(wr.startdate);}
                             if((wr.EndDate) !=null)
                            {relationshipInsert .End_Date__c = Date.valueof(wr.EndDate);}
                            
                             relationshipInsert .Status__c = getStatus(wr.status);
                             
                             relationshipInsert .isExist__c=true;
                             
                             Relist.add(relationshipInsert );
                        }
                       }
                        
                    }
                               
                } 
            }
            }
           
                system.debug('************'+Relist);
                If(Relist != null && Relist.size()>0)
                {
                    insert Relist;  
                }                                   
            }              
            system.debug('********'+Endresult);
            Endresult = 'Record inserted';
            }          
            else
            { 
                if(relwr==null){
                    Endresult='Contact cannot be imported since there is no relationship associated with this contact.';
                }
                else
                  Endresult = 'Contact cannot be imported since Account does not exist';
            }
                system.debug('Endresult----->'+Endresult);
                return Endresult;
            }  
          
          
    }